package net.ib.mtalk.ui.attachment.vcalendar;

import java.io.File;
import java.util.Date;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.UserMessage;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseActivity;
import net.ib.mtalk.constant.MTalkConstant;
import net.ib.mtalk.database.helper.ChatDatabaseHelper;
import net.ib.mtalk.ui.attachment.vcalendar.VCalendarStruct.EventStruct;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.TimeAdapter;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ReadVCalendarActivity extends BaseActivity {

	public static final String INTENT_MESSAGE_UUID_MSB = "intent_message_uuid_msb";
	public static final String INTENT_MESSAGE_UUID_LSB = "intent_message_uuid_lsb";
	
//	public ReadVCalendarAdapter 		cal_adapter 		= null;
//	private static String 				dateString			= null;
	private static EventStruct 			calendarEvents		= null;
	private static VCalendarStruct		calendarStruct 		= null;
//	private List<CalendarList> cal_items = new ArrayList<CalendarList>();
	
	private String uriStr = null;
	
	Context mContext;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		mContext = this;
		
		Bundle extras = getIntent().getExtras();
		
		long clientMsgUuidMsb = 0L;
		long clientMsgUuidLsb = 0L;
		
		if(extras != null && extras.containsKey(INTENT_MESSAGE_UUID_MSB)){
			clientMsgUuidMsb = extras.getLong(INTENT_MESSAGE_UUID_MSB);
		}else{
			this.finish();
			return;
		}
		if(extras != null && extras.containsKey(INTENT_MESSAGE_UUID_LSB)){
			clientMsgUuidLsb = extras.getLong(INTENT_MESSAGE_UUID_LSB);
		}else{
			this.finish();
			return;
		}
		
		UserMessage userMessage = ChatDatabaseHelper.getUserMessage(mContext, GpbSupport.makeUuidMsg(clientMsgUuidMsb, clientMsgUuidLsb));
		
		if(userMessage == null 
				|| !userMessage.hasAttachment()
				|| !userMessage.getAttachment().hasContent()
				|| !(userMessage.getAttachment().getMimeType().equals(MTalkConstant.MIME_TYPE_VCALENDAR))
				|| userMessage.getAttachment().getContent().toStringUtf8() == null){
			this.finish();
			return;
		}
		String vcalString = userMessage.getAttachment().getContent().toStringUtf8();
		if(vcalString == null || vcalString.equals("")){
			this.finish();
			return;
		}
		VCalendarMnParser mnParser = new VCalendarMnParser();
		calendarStruct = mnParser.parse(vcalString);
		
		calendarEvents = new EventStruct();
		
		setContentView(R.layout.layout_multimedia_calendar_receive);

		LinearLayout llTitle = (LinearLayout)findViewById(R.id.calendar_layout_title);
		LinearLayout llLocation = (LinearLayout)findViewById(R.id.calendar_layout_loaction);
		LinearLayout llAlarm = (LinearLayout)findViewById(R.id.calendar_layout_alarm);
		LinearLayout llDesc = (LinearLayout)findViewById(R.id.calendar_layout_desc);
		TextView tvTitle = (TextView)findViewById(R.id.calendar_title_id);
		TextView tvFrom = (TextView)findViewById(R.id.calendar_dtstart_id);
		TextView tvTo = (TextView)findViewById(R.id.calendar_dtend_id);
		TextView tvLocation = (TextView)findViewById(R.id.calendar_location_id);
		TextView tvAlarm = (TextView)findViewById(R.id.calendar_alarm_id);
		TextView tvDesc = (TextView)findViewById(R.id.calendar_desc_id);
		ImageView ivTitle = (ImageView)findViewById(R.id.calendar_divider_title);
		ImageView ivLocation = (ImageView)findViewById(R.id.calendar_divider_location);
		ImageView ivAlarm = (ImageView)findViewById(R.id.calendar_divider_alarm);
		ImageView ivDesc = (ImageView)findViewById(R.id.calendar_divider_desc);
		
		calendarEvents = calendarStruct.eventList.get(0);
		
		if(calendarEvents.title != null){
			tvTitle.setText(calendarEvents.title);
		}
		String dateString = null;
		if(calendarEvents.dtstart != null){
			Date startDate = TimeAdapter.UTC2Date(calendarEvents.dtstart.substring(0, calendarEvents.dtstart.length()-1));
			dateString = TimeAdapter.Date2Str(startDate, "EEE MMM dd, yyyy hh:mmaa");
			tvFrom.setText(dateString);
		}
		if(calendarEvents.dtend != null){
			Date endDate = TimeAdapter.UTC2Date(calendarEvents.dtend.substring(0, calendarEvents.dtend.length()-1));
			dateString = TimeAdapter.Date2Str(endDate, "EEE MMM dd, yyyy hh:mmaa");
			tvTo.setText(dateString);
//		}else if(calendarEvents.duration != null){
//			String dateStrTemp = calendarEvents.duration;
//			dateStrTemp = dateStrTemp.substring(1);
//			int temp = dateStrTemp.length();
//			dateStrTemp = dateStrTemp.substring(0, temp-1);
//			dateStrTemp += "000";
//			Long dateTemp = Long.parseLong(dateStrTemp) + Long.parseLong(calendarEvents.dtstart);
//			Date endDate = new Date(dateTemp);
//			String dateDurationString = getDateStr(endDate);
//			tvTo.setText(dateDurationString);
		}else{
			tvTo.setText(dateString);
		}
		if(calendarEvents.event_location != null){
			tvLocation.setText(calendarEvents.event_location);
		}else{
			llLocation.setVisibility(View.GONE);
			ivLocation.setVisibility(View.GONE);
		}
		if(calendarEvents.description != null){
			tvDesc.setText(calendarEvents.description);
		}else{
			llDesc.setVisibility(View.GONE);
			ivDesc.setVisibility(View.GONE);
		}
		if(calendarEvents.has_alarm != null){
			llAlarm.setVisibility(View.GONE);
			ivAlarm.setVisibility(View.GONE);
		}else{
			llAlarm.setVisibility(View.GONE);
			ivAlarm.setVisibility(View.GONE);
		}
		if(calendarEvents.last_date != null){

		}
		if(calendarEvents.rrule != null){

		}
		if(calendarEvents.status != null){

		}
		if(calendarEvents.uid != null){

		}
		if(calendarEvents.allDay != null){
			
		}
		if(calendarEvents.reminderList != null){
			
		}
		if(calendarEvents.timezone != null){
			
		}
		if(calendarEvents.timezone != null){
			
		}
		
		Button btnAdd = (Button) findViewById(R.id.vcalendar_btn_save);
        btnAdd.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				File checkSDCardDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
				if(!checkSDCardDirectory.canRead()){
					Toast.makeText(mContext, R.string.toast_sdcard_not_found, Toast.LENGTH_SHORT).show();
				}else{
					addCalendar();
				}
			}
		});
        
        Button btnCancel = (Button) findViewById(R.id.vcalendar_btn_cancel);
        btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	private void addCalendar(){
		String  contentProvider = "";
	    if(Build.VERSION.SDK_INT < 8){
	    	contentProvider = "calendar";
	    }else{
	    	contentProvider = "com.android.calendar";
	    }
    	
	    ContentResolver contentResolver = getApplicationContext().getContentResolver();

		//contentResolver 
		ContentValues values = new ContentValues();
		
		values.put("calendar_id", 1);
		if(calendarEvents.title != null){
			values.put("title", calendarEvents.title);			
		}
		if(calendarEvents.description != null){
			values.put("description", calendarEvents.description);
		}
		if(calendarEvents.event_location != null){
			values.put("eventLocation", calendarEvents.event_location);			
		}
		if(calendarEvents.dtstart != null){
			Date startDate = TimeAdapter.UTC2Date(calendarEvents.dtstart.substring(0, calendarEvents.dtstart.length()-1));
			values.put("dtstart", startDate.getTime());			
		}
		if(calendarEvents.dtend != null){
			Date endDate = TimeAdapter.UTC2Date(calendarEvents.dtend.substring(0, calendarEvents.dtend.length()-1));
			values.put("dtend", endDate.getTime());
		}
//		if(calendarEvents.duration != null){
//			values.put("duration", calendarEvents.duration);
//		}
		if(calendarEvents.rrule != null){
			values.put("rrule", calendarEvents.rrule);
		}
		if(calendarEvents.allDay != null){
			values.put("allDay", calendarEvents.allDay);
		}
		if(calendarEvents.has_alarm != null){
			values.put("hasAlarm", calendarEvents.has_alarm);
		}
		if(calendarEvents.status != null){
			values.put("eventStatus", calendarEvents.status);
		}
		if(calendarEvents.timezone != null){
			values.put("eventTimezone", calendarEvents.timezone);
		}
		if(calendarEvents.last_date != null){
			Date lastDate = TimeAdapter.UTC2Date(calendarEvents.last_date.substring(0, calendarEvents.last_date.length()-1));
			values.put("lastDate", lastDate.getTime());
		}

		Uri eventsUri = Uri.parse("content://"+contentProvider+"/events");
		contentResolver.insert(eventsUri, values);//getContentResolver().insert(eventsUri, values);
		
		CharSequence txt = "Calendar creation success.";
		Toast createToast = Toast.makeText(mContext, txt, Toast.LENGTH_SHORT);
		createToast.show();
		
		finish();
    }
}
